package org.ediba.siri.core.user.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.ediba.siri.core.user.domain.User;
import org.ediba.siri.core.user.domain.UserRole;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public class MyUserDetailsService implements UserDetailsService {

	private UserService userService;
	public void setUserService(UserService userService){this.userService = userService;}
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
		User _user = this.userService.retrieve(username);
		
		if (_user == null)
			throw new UsernameNotFoundException(username);
		else {
			List<UserRole> roles = this.userService.roleRetrieveForUser(_user.getId());
			Collection<GrantedAuthority> _grantedAuthorities = new ArrayList<GrantedAuthority>(roles.size());
			for (UserRole userRole : roles) 
				_grantedAuthorities.add(new GrantedAuthorityImpl(userRole.getName()));
			
			return new org.springframework.security.core.userdetails.User(_user.getName(),_user.getPassword(),true,true,true,true,_grantedAuthorities);
			
		}

	}

}
